﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class WikiFormPage : PhoneApplicationPage
    {
        private Wiki wiki;
        private Category kategori;
        public ObservableCollection<Category> kategoris;
        private object data = null;
        private bool firstLoaded;

        public WikiFormPage()
        {
            InitializeComponent();
            GetKategoriList();

            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                firstLoaded = false;
            else
                firstLoaded = true;
        }

        #region Event Handlers
        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            data = DataContext;
            if (firstLoaded)
            {
                if (data != null && data is Wiki)
                {
                    wiki = (Wiki)data;
                    if (wiki != null && wiki.Id != null)
                    {
                        textBoxJudul.Text = wiki.Judul;
                        textBoxIsi.Text = wiki.Isi;
                        if (kategoriList.ItemsSource != null)
                            kategoriList.SelectedItem = wiki.Kategori;
                        kategoriList.IsEnabled = false;
                        textBoxJudul.IsEnabled = false;
                    }
                    else
                    {
                        textBoxJudul.Text = "";
                        textBoxIsi.Text = "";
                        if (kategoriList.ItemsSource != null)
                            kategoriList.SelectedItem = wiki.Kategori;
                    }
                }
            }
        }

        #endregion

        private void GetKategoriList()
        {
            WebClient webClient = new WebClient();

            string url = Config.Instance.CATEGORY_SERVICE_URL() + Config.VIEW_ACTION_KEY;
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listKategori_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listKategori_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }
                kategoris = JsonConvert.DeserializeObject<ObservableCollection<Category>>(e.Result);
                kategoriList.ItemsSource = kategoris;
                if (wiki != null && wiki.Kategori != null)
                    kategoriList.SelectedItem = wiki.Kategori;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void CreateWiki(Wiki data)
        {
            string json = null, url = null;

            wiki = (Wiki)data;
            if (wiki.Id == null)
            {
                url = Config.Instance.WIKI_SERVICE_URL() + Config.ADD_ACTION_KEY;
            }
            else
            {
                url = Config.Instance.WIKI_SERVICE_URL() + Config.UPDATE_ACTION_KEY;
            }
            json = JsonConvert.SerializeObject(wiki);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveWiki_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveWiki_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxJudul.Text))
            {
                MessageBox.Show("Judul Wiki harus di isi!");
                return;
            }
            if (string.IsNullOrEmpty(textBoxIsi.Text))
            {
                MessageBox.Show("Isi Wiki harus di isi!");
                return;
            }
            if (data != null && data is Wiki)
            {
                Wiki wiki = (Wiki)data;
                wiki.Judul = textBoxJudul.Text;
                wiki.Isi = textBoxIsi.Text;
                wiki.Creator = SavedUser.Instance.User;

                wiki.Kategori = (Category)kategoriList.SelectedItem;

                CreateWiki(wiki);
            }
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}